Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
บทความนี้มาทำความรู้จักกับ Exception ที่ชื่อว่า ArrayIndexOutOfBoundsException กัน ซึ่งเวลาเกิด Exception จะมีข้อความแจ้งเตือนประมาณนี้Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at com.doesystem.CodeFromDoesystem.main(CodeFromDoesystem.java:11)
จากข้อความ Exception ข้างบนเราสามารถแปลข้อความบางส่วนได้ ดังนี้
Exception เกิด Exception
thread "main" ก็คือ thread ที่ชื่อว่า main
ArrayIndexOutOfBoundsException เกิด Exception ที่ชื่อว่า ArrayIndexOutOfBoundsException
เมื่อเรานำคำว่า ArrayIndexOutOfBoundsException มาแยกแปลแต่ละตัว จะได้ว่า
Array ก็คือ Array
Index ก็คือ index ของ Array
Out Of Bounds ก็คือ นอกเหนือไปจากตัวมัน นอกเหนือขอบเขตของมัน
Exception ก็คือ เกิด Exception
ดังนั้นจากข้อความแจ้ง Exception เราสามารถสรุปได้คร่าว ๆ ว่า เกิด Exception เกี่ยวกับ index ของ Array ที่นอกเหนือไปจากตัวมันหรือนอกเหนือขอบเขตของมัน
ดังนั้นลองมาดูโค้ดที่ทำให้เกิด Exception กัน
package com.doesystem; public class CodeFromDoesystem { public static void main(String[] args) throws Exception { String[] testArry = new String[]{"a", "b", "c", "d", "e"}; System.out.println(testArry[0]); System.out.println(testArry[1]); System.out.println(testArry[2]); System.out.println(testArry[3]); System.out.println(testArry[4]); System.out.println(testArry[5]); System.out.println(testArry[6]); } }
จากข้อความแจ้งเตือน CodeFromDoesystem.java:11 ให้เราไปดูที่บรรทัดที่ 11 จะเห็นว่าเป็นการ println ของ testArray ที่ index ที่ 5 แล้วเราลองมาดู testArray ว่ามี index กี่ตัว จากบรรทัดที่ 5 เราจะเห็นว่ามีการประกาศ testArray ไว้เป็น Array ชนิด String ที่มีจำนวน 5 ตัว ดังนั้นจะมี index ก็คือ 0, 1, 2, 3, 4 จึงทำให้รู้ว่าการเรีย testArray ที่ index ที่ 5 ไม่มีจึงทำให้เกิด Exception ดังนั้นก็ให้เราแก้ไขมันซะ
แต่เดี๋ยวก่อน? เมื่อเราแก้บรรทัดที่ 11 ซึ่งเป็นการเรียก index ที่ 5 ของ testArray ซึ่งเกิน index ของมันเราลองสังเกตบรรทัดที่ 12 มีการเรียก index ที่ 6 ของ testArray ดังนั้นบรรทัดนี้ก็เกิด index ด้วยให้เราแก้ด้วย